<template>
    <div class="page" style="min-height:0" v-if="hierarchyList.length">
       <div class="margin-cg">
          <scroller :lock-y="true" v-ref:scrollerdom>
            <div class="scroller-wrap">
                <div class="mod-crumbs bg-color">
                    <div class="weui-cell__bd ">
                        <div class="nav-item" v-for="(index,hierarchy) in hierarchyList" >
                        <span v-if="index!=0" class="arrow">&gt;</span>
                        <a v-if="index < hierarchyListLen" @click.prevent="stepHierarchy(index)" >{{hierarchy.department_name}}</a>
                        <template v-else>{{hierarchy.department_name}}</template>
                        </div>
                    </div>
                </div>
             </div>
           </scroller>
       </div>
  
    </div>
        <div v-show="admins.add_member"  class="list com-border-bottom" style="margin-top: 0;">
            <ul>
                <li class="com-border-bottom">
                    <a class="touch" @click="toAddMember">
                        <span class="bg_sprite icon icon_add_member"></span>
                        <div class="info">添加人员</div>
                    </a>
                </li>
                <li class="com-border-bottom">
                    <a @click="toAddGroup" class="touch">
                        <span class="bg_sprite icon icon_add_team"></span>
                        <div class="info">添加部门</div>
                    </a>
                </li>
            </ul>
        </div>
        <div class="list com-border-top com-border-bottom" v-if="teamListObj.sub_department.length">
            <ul>
                <template v-for="item in teamListObj.sub_department">
                    <li class="com-border-bottom" @click="gotoTeamGroupInfo(item.id,item.team_id,item.parent_id,item.name)">
                        <a class="touch" href="javascript:;">
                            <span class="bg_sprite icon icon_team"></span>
                            <div class="info">{{item.name}}</div>
                            <span class="arrow"></span>
                        </a>
                    </li>
                </template>
            </ul>
        </div>
        <!--成员列表-->
        <template v-if="teamListObj.department_user.length">
            <div class="list com-border-top com-border-bottom"> 
                <ul>
                    <li class="com-border-bottom" v-for="item in teamListObj.department_user">
                        <a class="touch" href="javascript:;" @click="gotoUserInfo(item.user_id,item.team_id,item.real_name,item.mobile,item.role_name,item.role)">
                            <template v-if="item.status == 1">
                                <img class="avatar" v-if="item.logo.thumb_url" :src="item.logo.thumb_url" alt="">
                                <img class="avatar" v-else src="http://sta.doumistatic.com/src/image/saas/avatar.png" alt=""> 
                                <div class="info" v-if="item.role == 5">
                                    <p class="title">{{item.real_name}}</p>
                                </div>
                                <div class="info" v-else>
                                    <p class="title"><span class="tag " :class="{tag_2:item.role == 8 , tag_1: (item.role == 1||item.role == 2)}">{{item.role_name}}</span>{{item.real_name}}</p>
                                </div>
                            </template>
                            <template v-if="item.status == 0">
                                <div class="avatar-box">
                                    <img class="avatar" v-if="item.logo.thumb_url" :src="item.logo.thumb_url" alt="">
                                    <img class="avatar" v-else src="http://sta.doumistatic.com/src/image/saas/avatar.png" alt=""> 
                                    <span class="cover">未激活</span>
                                </div>
                                <div class="info" v-if="item.role == 5">
                                    <p class="title">{{item.real_name}}</p>
                                </div>
                                <div class="info" v-else>
                                    <p class="title">{{item.real_name}}<span class="tag " :class="{tag_2:item.role == 8 , tag_1: (item.role == 1||item.role == 2)}">{{item.role_name}}</span></p>
                                </div>
                            </template>
                        </a>
                    </li>
                </ul>
            </div>
        </template>
        <div v-show="loading">
          <div class="weui-mask"></div>
          <div class="weui-toast">
              <i class="weui-loading weui-icon_toast"></i>
              <p class="weui-toast__content">数据加载中</p>
          </div>
        </div>
</template>

<script>
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import $ from 'zepto'
    import cache from 'gapi/cache.js'
    import commonPage from 'clientApi/commonPage.js'
    import * as util from 'js/util.js'
    import GroupUtil from 'js/GroupUtil.js'
    import widget from 'gapi/widget'
    import socialApi from 'clientApi/socialApi'
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */
    import Scroller from 'vux/dist/components/scroller'
    /**
     *  组件实例对象
     */
    export default {
        components: {
          Scroller
        },
        data: function(){
            return{
                ismembershow:false,
                notact:false,
                isAddMemberPerm: false,
                showHandleInvite : false,
                notActivation:[],
                hierarchyList:[],
                userList: [],
                grouplist: [],
                // cacheGroupList: [],
                actions: true,
                loading: false,
                group: {},
                parentWebViewId: '',
                webViewId:'',
                b_len:'',
                isadmins:'',
                admins:{
                    add_member:false,   // 是否有权添加人员和部门
                    admin_edit_team:false
                },
                user_id:'',
                currRole:'',
                teamListObj:{
                    department_id:'',
                    sub_department:[],
                    department_user:[]
                }
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
                //从urd中获取参数 groupid, grounpname
                this.id = util.getUrddataString('id') //id
                this.name = util.getUrddataString('gname') //grounpname
                this.tid = util.getUrddataString('teamId') //teamid
                this.parent_id = util.getUrddataString('parent_id') //parent_id  父级部门id
                this.user_id = util.getUrddataString('user_id')
                document.title = this.name //子小组页面title
                commonPage.getWebViewID((data)=>{
                    if(data){
                        this.webViewId = data
                    } 
                })
                // window.loadData = (data) => {
                //     this.getGroupList()
                // }
                // 获取权限
                this.getPermissions()
                //获取部门信息
                this.getGroupList()
            },
            //添加人员
            toAddMember() {
              let encodeStr = encodeURIComponent(`teamId=${this.tid}&groupName=${this.name}&type=${2}&department_id=${this.id}`)
                location.href = `dmsaas://AddMember?urdData=${encodeStr}`
            },
            //添加部门
            toAddGroup (){
                let url = `teamId=${this.tid}&department_id=${this.id}`
                window.location.href="dmsaas://TeamAddDepartment?urdData="+encodeURIComponent(url)
            }, 
            //前往成员信息
            gotoUserInfo (user_id,team_id,name,mobile,role_name,roleid){
               let str = `teamId=${this.tid}&user_id=${user_id}&department_id=${this.id}&name=${name}&mobile=${mobile}&role=${role_name}&currRole=${this.currRole}&currentLoginUserId=${this.user_id}&roleid=${roleid}`
                let encodeStr = encodeURIComponent(str)
                location.href = `dmsaas://MemberInfo?urdData=${encodeStr}`
            },
            //跳转下一级
             gotoTeamGroupInfo(id,teamid,parentid,gname){
                let str = `teamId=${teamid}&parent_id=${parentid}&gname=${gname}&id=${id}&webViewId=${this.webViewId}&user_id=${this.user_id}`
                let encodeStr = encodeURIComponent(str)
                location.href = `dmsaas://TeamGroupInfo?urdData=${encodeStr}`

            },
            //点击对应层级
           stepHierarchy(index){
               let cacheKey = `groupInfoWebView_${index}`;
               if (index == 0) {
                   cacheKey = 'teamGroupListWebViewID';
               }
                cache.getMemoryCache(cacheKey,(data)=>{
                    if(data){
                       commonPage.goBack(1,{'goBackKey':'index','value':index,'isadminsId':this.isadmins}, data.webViewID)
                    }
                })
            },
            //获取当前小组信息
            getGroupList (){
                util.ajax({
                    url:'/team/department_organ',
                    type:'GET',
                    data:{
                        team_id:this.tid,
                        department_id:this.id,  // 部门id
                        department_only:0
                    },
                    timeout:10000,
                    beforeSend: () => {
                        commonPage.loadPageStatus('loadSuccess')
                        this.loading = true
                    },
                    success:(obj) => {
                        console.log(obj)
                        commonPage.loadPageStatus('loadSuccess')
                        if(obj.errno == 0){
                            this.teamListObj.department_id = obj.data.department_id
                            this.teamListObj.sub_department = obj.data.sub_department
                            this.teamListObj.department_user = obj.data.department_user
                            this.hierarchyList = obj.data.breadcrumb
                            this.teamListObj.department_user.forEach((item)=>{
                                if(this.user_id == item.user_id){
                                    this.currRole = item.role_name
                                }
                            })
                            
                            commonPage.getWebViewID((data)=>{
                                var index = this.hierarchyList.length - 1;
                                cache.setMemoryCache(`groupInfoWebView_${index}`,{'webViewID':data})
                                cache.setMemoryCache(`childGroupWebView`,{'webViewID':data})
                                console.log(data)
                            })
                        }else{
                            widget.toast(result.errmsg)
                        }
                    },
                    error: (xhr, status) => {
                        commonPage.loadPageStatus('loadSuccess')
                        // error
                        let toastStr = ''
                        if(status == 'timeout'){
                            toastStr = '网络请求超时'
                        }else{
                            toastStr = '服务器异常'
                        }

                        widget.toast(toastStr)
                    },
                    complete: () => {
                        commonPage.loadPageStatus('loadSuccess')
                        this.loading = false
                    },
                    noNetwork: () => {
                        commonPage.loadPageStatus('loadSuccess')
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
              })
            },
            getPermissions(){
                commonPage.loadPageStatus('loading')
                util.ajax({
                    url:'/permission/application',
                    type:'GET',
                    data:{
                        team_id:this.tid,
                        project_id:0,
                        application_id:0
                    },
                    timeout:10000,
                    success:(obj) => {
                        console.log(JSON.stringify(obj))
                        commonPage.loadPageStatus('loadSuccess')
                        if(obj&&obj.errno == 0){
                            obj.data.forEach ( (i) => {
                                if(i.id_name && i.id_name == 'admin_add_member'){ 
                                    this.admins.add_member = true;
                                }
                                if(i.id_name && i.id_name == 'admin_edit_team'){
                                    this.admins.admin_edit_team = true
                                }

                            })
                            commonPage.updateTitleBar({
                              backAction: '',
                              leftDisplay: true,
                              leftText: '关闭',
                              leftAction: 'closePage',
                              rightDisplay: this.admins.admin_edit_team,
                              rightText: '设置',
                              rightAction: 'xmConfig'
                            })
                        }else{
                            widget.toast(obj.errmsg)
                        }
                    },
                    error: (xhr, status) => {
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('服务器异常')
                    },
                    noNetwork: () => {
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            }
        },
        created(){
            // window.closePage = function () {
            //     cache.getMemoryCache('memberViewId', (data) => {
            //         console.log(data)
            //         if(data){
            //             commonPage.goBack(1,{},data.webViewID)
            //         } 
            //     })
            // }
           
            this.init();
            this.parentWebViewId = util.getUrddataString('webViewId')

            window.loadData = (data)=>{
                console.log(data)
                if(data && data.groupName){
                  // 更新title
                  this.hierarchyList = []
                  document.title = data.groupName   
                }
                if(data && data.key == 'changeCurrRole'){
                    this.isadmins = 99
                    commonPage.loadPageStatus('loading')
                    util.ajax({
                        url:'/permission/application',
                        type:'GET',
                        data:{
                            team_id:this.tid,
                            project_id:0,
                            application_id:0
                        },
                        timeout:10000,
                        success:(obj) => {
                            console.log(JSON.stringify(obj))
                            commonPage.loadPageStatus('loadSuccess')
                            if(obj&&obj.errno == 0){
                                obj.data.forEach ( (i) => {
                                    if(i.id_name && i.id_name == 'admin_add_member'){ 
                                        this.admins.add_member = true;
                                    }else{
                                        this.admins.add_member = false;
                                    }
                                    if(i.id_name && i.id_name == 'admin_edit_team'){
                                        this.admins.admin_edit_team = true
                                    }else{
                                        this.admins.admin_edit_team = false
                                    }

                                })
                                commonPage.updateTitleBar({
                                  backAction: '',
                                  leftDisplay: true,
                                  leftText: '关闭',
                                  leftAction: 'closePage',
                                  rightDisplay: this.admins.admin_edit_team,
                                  rightText: '设置',
                                  rightAction: 'xmConfig'
                                })
                            }else{
                                widget.toast(obj.errmsg)
                            }
                        },
                        error: (xhr, status) => {
                            commonPage.loadPageStatus('loadSuccess')
                            widget.toast('服务器异常')
                        },
                        noNetwork: () => {
                            commonPage.loadPageStatus('loadSuccess')
                            widget.toast('网络连接失败，请检查网络')
                        }
                    })
                }
                if(data && data.isadminsId == 99){
                    this.isadmins = 99
                    commonPage.loadPageStatus('loading')
                    util.ajax({
                        url:'/permission/application',
                        type:'GET',
                        data:{
                            team_id:this.tid,
                            project_id:0,
                            application_id:0
                        },
                        timeout:10000,
                        success:(obj) => {
                            console.log(JSON.stringify(obj))
                            commonPage.loadPageStatus('loadSuccess')
                            if(obj&&obj.errno == 0){
                                obj.data.forEach ( (i) => {
                                    if(i.id_name && i.id_name == 'admin_add_member'){ 
                                        this.admins.add_member = true;
                                    }else{
                                        this.admins.add_member = false;
                                    }
                                    if(i.id_name && i.id_name == 'admin_edit_team'){
                                        this.admins.admin_edit_team = true
                                    }else{
                                        this.admins.admin_edit_team = false
                                    }

                                })
                                commonPage.updateTitleBar({
                                  backAction: '',
                                  leftDisplay: true,
                                  leftText: '关闭',
                                  leftAction: 'closePage',
                                  rightDisplay: this.admins.admin_edit_team,
                                  rightText: '设置',
                                  rightAction: 'xmConfig'
                                })
                            }else{
                                widget.toast(obj.errmsg)
                            }
                        },
                        error: (xhr, status) => {
                            commonPage.loadPageStatus('loadSuccess')
                            widget.toast('服务器异常')
                        },
                        noNetwork: () => {
                            commonPage.loadPageStatus('loadSuccess')
                            widget.toast('网络连接失败，请检查网络')
                        }
                    })
                }
                this.getGroupList()
            }
        },
        ready(){
            window.xmConfig = () => {
              let str = encodeURIComponent(`teamId=${this.tid}&department_id=${this.id}&webViewId=${this.parentWebViewId}`)
              location.href = `dmsaas://TeamDepartmentSetting?urdData=${str}`
            }
            window.closePage = function () {
                cache.getMemoryCache('teamGroupListWebViewID', (data) => {
                    if(data){
                        commonPage.goBack(1,{},data.webViewID)
                    } 
                })
            }
        },
        watch: {
          'hierarchyList': function(){
            let allWidth = 0
            this.$nextTick(function () {
              if($('.scroller-wrap .nav-item').length){
                $('.scroller-wrap .nav-item').each(function(i, o){
                  // alert($(o).width() + '--' + o.tagName)
                  allWidth += parseInt(o.offsetWidth)
                })
                allWidth += 30
                $('.scroller-wrap').width(allWidth + 'px')

                this.$refs.scrollerdom.reset()
              }
            })
          }
        },
        computed : {
            hierarchyListLen() {
                return this.hierarchyList.length - 1;
            }
        }
    }


</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/user-list.css"></style>
<style>
  .scroller-wrap .nav-item{
    float: left;
  }
  .xs-container{
    background: #fff;
  }
</style>
